using System;
using System.Collections;
using System.Collections.Generic;
using System.Threading.Tasks;
using Cysharp.Threading.Tasks;
using ResourceFrame;
using UnityEngine;
using YooAsset;

//资源自动化管理
public class ResManager : Singleton<ResManager>
{
    private YooAssetHelper _assetHelper;
    private Dictionary<string, ResAutoRefData> _autoRefData;
    private readonly List<string> _removeHandle =  new List<string>();
    protected override void OnInit()
    {
        _assetHelper = YooAssetHelper.Instance;
        _autoRefData = new  Dictionary<string, ResAutoRefData>();
    }
    
    //异步加载资源
    public async void LoadAssetAsync<T>(string path,GameObject refObj,Action<T> call)where T : UnityEngine.Object
    {
        AssetHandle assetHandle = _assetHelper.Package.LoadAssetAsync<T>(path);
        await assetHandle.Task;
        if (assetHandle.AssetObject == null)
        {
            Debug.LogError($"资源加载错误LoadAssetAsync:{path}");
            return;
        }

        if (!_autoRefData.TryGetValue(path, out ResAutoRefData resAutoRefData))
        {
            resAutoRefData = new ResAutoRefData(assetHandle);
            _autoRefData.Add(path, resAutoRefData);
        }
        resAutoRefData.RefObj.Add(refObj);
        T asset = assetHandle.AssetObject as T;
        call?.Invoke(asset);
    }
    
    //释放引用计数为0的资源
    public async UniTask UnloadAsset()
    {
        //因为GameObject销毁是在本帧的最后阶段才会消耗，所以要等待帧结束
        await UniTask.WaitForEndOfFrame();
        _removeHandle.Clear();
        foreach (string path in _autoRefData.Keys)
        {
            ResAutoRefData resAutoRef = _autoRefData[path];
            List<GameObject> refObjs = resAutoRef.RefObj;
            int refIndex = 0;
            foreach (GameObject refObj in refObjs)
            {
                if (refObj != null)
                {
                    refIndex++;
                    break;
                }
            }
            if (refIndex == 0)
            {
                resAutoRef.Handle.Release();
                _removeHandle.Add(path);
            }
        }

        //移除资源的加载
        if (_removeHandle.Count != 0)
        {
            foreach (string path in _removeHandle)
            {
                _autoRefData.Remove(path);
            }
        }
        UnloadUnusedAssetsOperation unloadUnused = _assetHelper.Package.UnloadUnusedAssetsAsync();
        await unloadUnused.Task;
    }
}
